#include "my_timer.h"
#define timer_divider   80
#define timer_go_handler   (80000000/timer_divider)

uint64_t  timer_count = 0;

static bool IRAM_ATTR timer_group_isr_callback(void *args);


void my_timer_init(void)
{
    timer_config_t timer_config_str;
    timer_config_str.divider = timer_divider;     //分频值，默认时钟是80mhz,80mhz/80=1mhz=1us
    timer_config_str.counter_dir = TIMER_COUNT_UP;//向上计数模式
    timer_config_str.counter_en = TIMER_PAUSE;//定时器计数失能
    timer_config_str.alarm_en = TIMER_ALARM_EN;//使能定时器报警
    timer_config_str.auto_reload = 1;  //使能自动装载
    timer_init(TIMER_GROUP_0,TIMER_0,&timer_config_str);//esp32定时器共有两组，每组两个
    timer_set_counter_value(TIMER_GROUP_0, TIMER_0, 0);//设置定时器的计数值
    timer_set_alarm_value(TIMER_GROUP_0, TIMER_0, 100000);//设置定时器的报警值(进入中断的值)
    timer_enable_intr(TIMER_GROUP_0, TIMER_0);//使能定时器中断
    timer_isr_callback_add(TIMER_GROUP_0, TIMER_0, timer_group_isr_callback, NULL, ESP_INTR_FLAG_IRAM);
    // timer_isr_callback_add(TIMER_GROUP_0, TIMER_0,  timer_group_isr_callback, NULL,0);//添加定时器中断回调
    timer_start(TIMER_GROUP_0, TIMER_0);//打开定时器
    printf("打开定时器成功");
}
extern uint8_t io_state;
uint64_t  timer_count_value;
static bool IRAM_ATTR timer_group_isr_callback(void *args)
{

    BaseType_t pxHigherPriorityTaskWoken = pdFALSE;

	// uint32_t timer_intr = timer_group_get_intr_status_in_isr(TIMER_GROUP_0); //获取中断状态
	// if (timer_intr & TIMER_INTR_T0) {//定时器0分组的0号定时器产生中断
	//         /*清除中断状态*/
	//     timer_group_clr_intr_status_in_isr(TIMER_GROUP_0, TIMER_0);
	//         /*重新使能定时器中断*/
	//     timer_group_enable_alarm_in_isr(TIMER_GROUP_0, TIMER_0);
	// }
    // printf("LED反转%llu次\n",timer_count_value++);
    io_state = ! io_state;
    gpio_set_level(led_gpio,io_state);
    timer_count++;
    return pxHigherPriorityTaskWoken;
}


void print_timer_counter(uint64_t counter_value)
{
    // printf("Counter: 0x%u%u\r\n", (uint32_t) (counter_value >> 32),
    //        (uint32_t) (counter_value));
    printf("Time   : %.8f s\r\n", (double) counter_value / timer_go_handler);
    printf("%llu\n",counter_value);
}